最近跟工作室的其他學員一起開發新的專案,由於之前我都是用StoryBoard在開發,這次想說給自己一個挑戰-Programmatic UI(使用程式碼刻UI介面)。
剛好這次有使用到CollectionView,所以就來講講要怎麼在同個頁面顯示不同的CollectionView。
由於程式碼刻的UI複用性高,所以基本上刻完一個UICollectionView之後只要複製貼上再稍作修改就可以了。
首先先實作一個UICollectionView出來,用StoryBoard拉元件真的很快,Programmatic真的很麻煩...
先宣告一個UICollectionView
var firstCollectionView: UICollectionView!
然後開始對這個firstCollectionView上下其手,為所欲為,不,是設置layout,沒有設置可是會crash給你看!
 ///設定卡片firstCollectionView
    func setUpFirstCollectionView()
    {
        let viewFrame = UIScreen.main.bounds
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        
        // section與section之間的距離(如果只有一個section,可以想像成frame) 沒影響
        layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        
        // cell的寬、高
        layout.itemSize = CGSize(width: UIScreen.main.bounds.width * 0.75,
                                 height: viewFrame.height * 0.45)
        
        // cell與cell的間距
        layout.minimumLineSpacing = CGFloat(integerLiteral: Int(viewFrame.width * 0.05))
        
        // cell與邊界的間距,我調整過,但是不會更改,預設值是10
                layout.minimumInteritemSpacing = CGFloat(integerLiteral: 10)
        
        //滑動方向預設為垂直。注意若設為垂直,則cell的加入方式為由左至右,滿了才會換行;若是水平則由上往下,滿了才會換列
        layout.scrollDirection = UICollectionView.ScrollDirection.horizontal
        
        //        設定collectionView的大小
        self.firstCollectionView = UICollectionView(frame: CGRect(
            x: 0,
            y: (viewFrame.height * 0.4),   //
            width: viewFrame.width ,
            height: (viewFrame.height * 0.5)),
                                                    collectionViewLayout: layout)
        self.firstCollectionView.dataSource = self
        self.firstCollectionView.delegate = self
        self.firstCollectionView.register(CardCell.self, forCellWithReuseIdentifier: CollectionViewCellIdentifier.firstCell.identifier)
        
        self.firstCollectionView.backgroundColor = .lightGray
        self.view.addSubview(firstCollectionView)
    }
    
}
你肯定會對這一行有所疑問:self.firstCollectionView.register(CardCell.self, forCellWithReuseIdentifier: CollectionViewCellIdentifier.firstCell.identifier)
我用一個Enum去包裝我的Identifier因為考量到可能手殘打錯字,或者之後需要更改時,只要改一個地方就好,包裝的方法如下:
enum CollectionViewCellIdentifier: String
{
    case firstCell, secondCell
    var identifier: String
    {
        switch self
        {
        case .firstCell: return "firstCell"
        case .secondCell: return "secondCell"
        }
    }
}
剩下的cell設置、委派、資料源這些礙於篇幅,我打算明天再講。